package com.yshebkb.sulp.service;

import com.yshebkb.sulp.config.AppProperties;
import com.yshebkb.sulp.dao.MenuMapper;
import com.yshebkb.sulp.dao.UserMapper;
import com.yshebkb.sulp.entity.Menu;
import com.yshebkb.sulp.entity.Role;
import com.yshebkb.sulp.entity.User;
import com.yshebkb.sulp.exception.AppException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yshebkb
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private AppProperties appProperties;

    @Autowired
    private MenuMapper menuMapper;

    public List<User> findAll() {
        return userMapper.findAll();
    }

    public User findUserByUsername(String name) {
        return userMapper.findByName(name);
    }

    public void save(User user) {
        userMapper.insertSelective(user);
    }

    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    public User findUserByUserId(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public void deleteById(Long id) {
        User dbUser = findUserByUserId(id);
        if (dbUser == null) {
            throw new AppException(0, "用户不存在");
        }
        if (dbUser.getName().equals(appProperties.getSysAdmin())){
            throw new AppException(0, "超级管理员不允许删除");
        }
        userMapper.deleteByPrimaryKey(id);
    }

    public Set<String> getPerms(Long userId) {
        List<String> permsList = new ArrayList<>();

        List<Role> roles = userMapper.selectByPrimaryKey(userId).getRoles();

        Set<String> roleSet = roles.stream().map(Role::getName).collect(Collectors.toSet());

        //系统管理员，拥有最高权限
        if (roleSet.contains(appProperties.getSysAdmin())) {
            List<Menu> menus = menuMapper.findAll();
            for (Menu menu : menus) {
                permsList.add(menu.getPerms());
            }
        } else {
            for (Role role : roles) {
                List<Menu> menus = menuMapper.selectAllMenus(role.getId());
                for (Menu menu : menus) {
                    permsList.add(menu.getPerms());
                }
            }
        }

        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }
}
